<template>
  <div class="temperature-monitor-compact" :class="layoutClass">
    <!-- 实时温度图表 -->
    <el-card class="chart-card compact" body-style="padding: 8px;">
      <template #header>
        <div class="card-header compact">
          <div class="chart-title-section">
            <span class="chart-title">实时监测</span>
<!--            <div class="monitor-time" v-if="currentMonitorTime">{{ formatDisplayTime(currentMonitorTime) }}</div>-->
            <div class="filter-controls">
              <el-form :inline="true" :model="filterForm" size="mini" class="compact-form">
                <el-form-item label="通道" style="margin-bottom: 0 !important;">
                  <el-select v-model="filterForm.deviceNo" placeholder="请选择设备" @change="handleDeviceChange" style="width: 90px">
                    <el-option
                      v-for="device in deviceList"
                      :key="device.value"
                      :label="device.label"
                      :value="device.value"
                    />
                  </el-select> -
                  <el-select v-model="filterForm.channelNo" placeholder="请选择通道" @change="handleChannelChange" style="width: 90px">
                    <el-option
                      v-for="channel in channelList"
                      :key="channel.value"
                      :label="channel.label"
                      :value="channel.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item style="margin-bottom: 0 !important;">
                  <el-button type="primary" size="mini" icon="el-icon-refresh" @click="handleRefreshData">刷新</el-button>
                </el-form-item>
                <el-form-item style="margin-bottom: 0 !important;">
                  <el-button type="primary" size="mini" icon="el-icon-position" @click="applyZoomToTrend">应用</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="chart-legend">
            <div class="legend-item">
              <span class="legend-color normal"></span>
              <span>正常</span>
            </div>
            <div class="legend-item">
              <span class="legend-color warning"></span>
              <span>预警</span>
            </div>
            <div class="legend-item">
              <span class="legend-color danger"></span>
              <span>报警</span>
            </div>
          </div>
        </div>
      </template>
      <div id="realtimeChart" style="height: 200px;"></div>
    </el-card>

    <!-- 选定米标范围温度趋势 -->
    <el-card class="chart-card compact" body-style="padding: 8px;">
      <template #header>
        <div class="card-header compact">
          <div class="trend-header-left">
            <span class="chart-title">温度趋势</span>
            <span class="meter-range" v-if="selectedRange.length > 0">
              ({{ selectedRange[0] }} - {{ selectedRange[1] }}米)
            </span>
          </div>
          <div class="trend-header-right">
            <el-button size="mini" @click="showCurveSelector">
              选择展示曲线（{{ temperatureThreshold }}°C 以上）
            </el-button>
            <span class="time-range">
              {{ currentMonitorTime ? `监视时间: ${formatDisplayTime(currentMonitorTime)} | ` : '' }}
<!--              {{ timeRangeText }} | 共{{ displayedCurvesCount }}条曲线-->
            </span>
          </div>
        </div>
      </template>

      <!-- 时间查询条件 -->
      <div class="time-query-section single-line">
        <div class="query-type-buttons">
          <el-radio-group v-model="timeQuery.activeTab" size="mini" @change="handleTimeTabChange">
            <el-radio-button label="hour">按小时</el-radio-button>
            <el-radio-button label="day">按天</el-radio-button>
<!--            <el-radio-button label="month">按月</el-radio-button>-->
          </el-radio-group>
        </div>

        <div class="query-controls">
          <!-- 按小时查询条件 -->
          <div v-if="timeQuery.activeTab === 'hour'" class="query-control-group">
            <span class="query-label">最近</span>
            <el-input-number
              v-model="timeQuery.hour.hours"
              :min="1"
              :max="24"
              controls-position="right"
              size="mini"
              style="width: 80px;"
              @change="onTimeRangeChange"
            ></el-input-number>
            <span class="query-unit">小时</span>
          </div>

          <!-- 按天查询条件 -->
          <div v-if="timeQuery.activeTab === 'day'" class="query-control-group">
            <span class="query-label">日期范围</span>
            <el-date-picker
              v-model="timeQuery.day.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              size="mini"
              style="width: 220px;"
              @change="onTimeRangeChange"
            ></el-date-picker>
          </div>

          <!-- 按月查询条件 -->
<!--          <div v-if="timeQuery.activeTab === 'month'" class="query-control-group">-->
<!--            <span class="query-label">月份范围</span>-->
<!--            <el-date-picker-->
<!--              v-model="timeQuery.month.monthRange"-->
<!--              type="monthrange"-->
<!--              range-separator="至"-->
<!--              start-placeholder="开始月份"-->
<!--              end-placeholder="结束月份"-->
<!--              value-format="yyyy-MM"-->
<!--              size="mini"-->
<!--              style="width: 220px;"-->
<!--              @change="onTimeRangeChange"-->
<!--            ></el-date-picker>-->
<!--          </div>-->
        </div>

        <div class="query-button">
          <el-button type="primary" size="mini" @click="handleTimeQuery">查询</el-button>
        </div>
      </div>

      <!-- 趋势图容器 -->
      <div class="trend-chart-container">
        <div id="trendChart" style="height: 220px; flex: 1;"></div>
        <div class="curve-list-panel">
          <div class="curve-list-header">
            <span>曲线列表 ({{ displayedCurvesCount }})</span>
            <el-button size="mini" @click="clearAllHighlights">取消高亮</el-button>
          </div>
          <div class="curve-list-content">
            <div
              class="curve-list-item"
              v-for="curve in displayedCurves"
              :key="curve.meter"
              :class="{ 'highlighted': highlightedCurves.includes(curve.meter) }"
              @click.stop="toggleCurveHighlight(curve.meter)"
            >
              <div class="curve-color-indicator" :style="{ backgroundColor: curve.color }"></div>
              <div class="curve-info">
                <div class="meter-number">米标{{ curve.meter }}</div>
                <div class="max-temperature">最高: {{ curve.maxTemp }}°C</div>
              </div>
            </div>
            <div v-if="displayedCurves.length === 0" class="empty-list">
              暂无曲线数据
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 曲线选择对话框 -->
    <el-dialog
      title="选择展示的温度曲线"
      :visible.sync="curveSelectorVisible"
      width="800px"
      :before-close="handleCurveSelectorClose"
      custom-class="compact-dialog"
    >
      <div class="curve-selector-content">
        <div class="selector-header">
          <span>已选择米标范围: {{ selectedRange[0] }} - {{ selectedRange[1] }}米</span>
          <div class="selector-actions">
            <el-input-number
              v-model="temperatureThreshold"
              size="mini"
              :min="20"
              :max="100"
              :step="1"
              controls-position="right"
              style="width: 90px; margin-right: 8px;"
            />
            <el-button size="mini" @click="selectTempCurves" type="primary">选择温度≥{{ temperatureThreshold  }}°C曲线</el-button>
          </div>
        </div>

        <div class="curve-selector-layout">
          <div class="curve-panel available-curves">
            <div class="panel-header">
              <span>待选择曲线 ({{ availableCurvesList.length }})</span>
              <el-button size="mini" @click="selectAllCurves">全选</el-button>
            </div>
            <div class="curve-list">
              <div
                class="curve-item"
                v-for="meter in availableCurvesList"
                :key="meter.meter"
                @click="toggleCurveSelection(meter)"
              >
                <div class="curve-info">
                  <span class="meter-number">米标{{ meter.meter }}</span>
                  <span class="temperature" :class="{ 'high-temp': meter.temperature > temperatureThreshold  }">
                    {{ meter.temperature }}°C
                  </span>
                </div>
                <i class="el-icon-arrow-right select-icon"></i>
              </div>
            </div>
          </div>

          <div class="transfer-actions">
            <el-button
              type="primary"
              icon="el-icon-arrow-right"
              circle
              size="mini"
              @click="moveAllToSelected"
            ></el-button>
            <el-button
              icon="el-icon-arrow-left"
              circle
              size="mini"
              @click="moveAllToAvailable"
              style="margin-top: 8px;"
            ></el-button>
          </div>

          <div class="curve-panel selected-curves">
            <div class="panel-header">
              <span>已选择曲线 ({{ selectedCurvesList.length }})</span>
              <el-button size="mini" @click="clearAllCurves">清空</el-button>
            </div>
            <div class="curve-list">
              <div
                class="curve-item"
                v-for="meter in selectedCurvesList"
                :key="meter.meter"
                @click="toggleCurveSelection(meter)"
              >
                <i class="el-icon-arrow-left remove-icon"></i>
                <div class="curve-info">
                  <span class="meter-number">米标{{ meter.meter }}</span>
                  <span class="temperature" :class="{ 'high-temp': meter.temperature > temperatureThreshold }">
                      {{ meter.temperature }}°C
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="curveSelectorVisible = false">取消</el-button>
        <el-button type="primary" size="mini" @click="confirmCurveSelection">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {
  getRealtimeTemperatureData,
  getMeterRangeTemperatureData,
  getDevicesAndChannels
} from '@/api/project/monitor';

export default {
  name: 'TemperatureMonitor',
  props: {
    // 布局配置：'row' 表示一行，'column' 表示两行
    layout: {
      type: String,
      default: 'column',
      validator: (value) => ['row', 'column'].includes(value)
    }
  },
  data() {
    return {
      currentMonitorTime: null,
      filterForm: {
        deviceNo: '001',
        channelNo: 1
      },
      deviceList: [],
      channelList: [],
      realtimeChart: null,
      trendChart: null,
      selectedRange: [1, 100],
      displayedCurvesCount: 0,
      currentZoomRange: { start: 0, end: 100 },
      currentTemperatureData: null,
      timeQuery: {
        activeTab: 'hour',
        hour: {
          hours: 1
        },
        day: {
          dateRange: []
        },
        month: {
          monthRange: []
        }
      },
      timeRangeText: '最近1小时数据',
      curveSelectorVisible: false,
      availableCurves: [],
      selectedCurves: [],
      temperatureThreshold: 60,
      highlightedCurves: [],
      trendDataCache: null,
      displayedCurves: [],
      trendStartTime: '',
      trendEndTime: ''
    };
  },
  computed: {
    layoutClass() {
      return {
        'layout-row': this.layout === 'row',
        'layout-column': this.layout === 'column'
      };
    },
    selectedCurvesCount() {
      return this.selectedCurvesList.length;
    },
    selectedCurvesList() {
      return this.availableCurves.filter(curve => curve.selected);
    },
    availableCurvesList() {
      return this.availableCurves.filter(curve => !curve.selected);
    }
  },
  mounted() {
    this.initData();
    this.initCharts();
    this.initDefaultTimeRange();
  },
  beforeDestroy() {
    if (this.realtimeChart) {
      this.realtimeChart.dispose();
    }
    if (this.trendChart) {
      this.trendChart.dispose();
    }
  },
  methods: {
    // 初始化数据
    async initData() {
      const devicesData = await this.loadDeviceChannels();
      if (this.deviceList.length > 0) {
        this.filterForm.deviceNo = this.deviceList[0].value;
        await this.handleDeviceChange(devicesData);
      }
    },

    // 加载设备和通道数据
    async loadDeviceChannels() {
      try {
        const response = await getDevicesAndChannels();
        const devicesData = response.data;

        if (devicesData?.length > 0) {
          this.deviceList = [...new Set(devicesData.map(item => item.deviceNo))].map(deviceNo => ({
            label: `设备${deviceNo}`,
            value: deviceNo
          }));

          if (this.deviceList.length > 0) {
            this.filterForm.deviceNo = this.deviceList[0].value;
            this.updateChannelList(this.filterForm.deviceNo, devicesData);
          }
        }
        return devicesData || [];
      } catch (error) {
        console.error('加载设备通道失败:', error);
        this.$message.error('加载设备通道失败');
        return [];
      }
    },

    // 更新通道列表
    updateChannelList(deviceNo, devicesData) {
      this.channelList = devicesData
        .filter(item => item.deviceNo === deviceNo)
        .map(channel => ({
          label: `通道${channel.channelNo}`,
          value: channel.channelNo,
          startMeter: Number(channel.startMeter) || 1,
          endMeter: Number(channel.endMeter) || 1500
        }));

      if (this.channelList.length > 0) {
        this.filterForm.channelNo = this.channelList[0].value;
        const channel = this.channelList[0];
        this.selectedRange = [channel.startMeter, channel.endMeter];
      }
    },

    // 设备变更处理
    async handleDeviceChange(devicesData = null) {
      if (devicesData) {
        this.updateChannelList(this.filterForm.deviceNo, devicesData);
      } else {
        const response = await getDevicesAndChannels();
        this.updateChannelList(this.filterForm.deviceNo, response.data);
      }
      await this.loadRealtimeData();
    },

    // 通道变更处理
    async handleChannelChange() {
      const channel = this.channelList.find(c => c.value === this.filterForm.channelNo);
      if (channel) {
        this.selectedRange = [Number(channel.startMeter), Number(channel.endMeter)];
      }
      await this.loadRealtimeData();
    },

    // 刷新数据
    async handleRefreshData() {
      if (!this.filterForm.deviceNo || !this.filterForm.channelNo) {
        this.$message.warning('请先选择设备和通道');
        return;
      }

      try {
        await this.loadRealtimeData();
        this.$message.success('数据刷新成功');
      } catch (error) {
        console.error('刷新数据失败:', error);
        this.$message.error('刷新数据失败');
      }
    },

    // 加载实时数据
    async loadRealtimeData() {
      if (!this.filterForm.deviceNo || !this.filterForm.channelNo) {
        return;
      }

      try {
        const response = await getRealtimeTemperatureData(
          this.filterForm.deviceNo,
          this.filterForm.channelNo
        );

        if (response.data && response.data.length > 0) {
          const latestData = response.data[response.data.length - 1];
          this.currentMonitorTime = latestData.createTime;
          this.calculateTimeRange();
          this.processRealtimeChartData(latestData);
          await this.applyZoomToTrend();
        } else {
          this.$message.warning('暂无实时温度数据');
          this.currentMonitorTime = null;
        }
      } catch (error) {
        console.error('加载实时数据失败:', error);
        this.$message.error('加载实时数据失败');
        this.currentMonitorTime = null;
      }
    },

    // 处理实时图表数据
    processRealtimeChartData(temperatureData) {
      if (!temperatureData || !temperatureData.maxTemperatureList) {
        this.$message.warning('温度数据格式错误');
        return;
      }

      const currentChannel = this.channelList.find(c => c.value === this.filterForm.channelNo);
      const startMeter = currentChannel ? Number(currentChannel.startMeter) : 1;
      const endMeter = currentChannel ? Number(currentChannel.endMeter) : 1500;

      const meterPoints = [];
      const temperaturePoints = [];
      const colors = [];

      const maxTemps = temperatureData.maxTemperatureList;
      const actualMeterCount = Math.min(maxTemps.length, endMeter - startMeter + 1);

      for (let i = 0; i < actualMeterCount; i++) {
        const currentMeter = startMeter + i;
        meterPoints.push(currentMeter);

        const temp = maxTemps[i];
        temperaturePoints.push(temp);

        if (temp >= this.temperatureThreshold) {
          colors.push('#ff4d4f');
        } else if (temp > 60) {
          colors.push('#faad14');
        } else {
          colors.push('#1890ff');
        }
      }

      this.updateRealtimeChart(meterPoints, temperaturePoints, colors);

      this.currentTemperatureData = {
        meterPoints,
        temperaturePoints,
        colors,
        rawData: temperatureData,
        startMeter,
        endMeter
      };

      const totalMeters = meterPoints.length;
      const defaultZoomRange = totalMeters <= 100 ? 100 : (100 / totalMeters) * 100;

      this.realtimeChart.setOption({
        dataZoom: [
          {
            start: 0,
            end: defaultZoomRange
          },
          {
            start: 0,
            end: defaultZoomRange
          }
        ]
      });

      this.currentZoomRange = {start: 0, end: defaultZoomRange};
      this.updateSelectedRangeFromZoom();
      this.initCurveSelectionData(meterPoints, temperaturePoints);
    },

    // 更新选中范围
    updateSelectedRangeFromZoom() {
      if (!this.currentTemperatureData || !this.currentTemperatureData.meterPoints) {
        return;
      }

      const meterPoints = this.currentTemperatureData.meterPoints;
      const totalMeters = meterPoints.length;

      const startIndex = Math.floor((this.currentZoomRange.start / 100) * totalMeters);
      const endIndex = Math.floor((this.currentZoomRange.end / 100) * totalMeters);

      const actualStartIndex = Math.max(0, startIndex);
      const actualEndIndex = Math.min(totalMeters - 1, endIndex);

      const startMeter = meterPoints[actualStartIndex];
      const endMeter = meterPoints[actualEndIndex];

      this.selectedRange = [startMeter, endMeter];
    },

    // 初始化曲线选择数据
    initCurveSelectionData(meterPoints, temperaturePoints) {
      const selectedMeters = [];
      for (let i = 0; i < meterPoints.length; i++) {
        selectedMeters.push({
          meter: meterPoints[i],
          temperature: temperaturePoints[i],
          selected: temperaturePoints[i] > this.temperatureThreshold
        });
      }
      this.availableCurves = selectedMeters;
      this.selectedCurves = selectedMeters.filter(meter => meter.selected).map(meter => meter.meter);
      this.displayedCurvesCount = this.selectedCurves.length;
    },

    // 初始化图表
    initCharts() {
      this.initRealtimeChart();
      this.initTrendChart();
    },

    // 初始化实时图表
    initRealtimeChart() {
      const chartDom = document.getElementById('realtimeChart');
      if (!chartDom) return;

      this.realtimeChart = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const data = params[0];
            // 简化显示：只显示米标和温度
            return `米标: ${data.name}<br/>温度: ${data.value}°C`;
          },
          extraCssText: 'z-index: 1;'
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100,
            zoomLock: false,
            moveOnMouseMove: true
          },
          {
            show: true,
            type: 'slider',
            height: 16,
            bottom: 0,
            start: 0,
            end: 100,
            handleSize: 10,
            brushSelect: false,
            zoomLock: false
          }
        ],
        xAxis: {
          type: 'category',
          data: [],
          name: '米标位置',
          nameLocation: 'middle',
          nameGap: 20,
          axisLabel: {
            fontSize: 9
          }
        },
        yAxis: {
          type: 'value',
          name: '温度 (°C)',
          min: 20,
          max: 100,
          axisLabel: {
            fontSize: 9
          }
        },
        series: [
          {
            name: '温度',
            type: 'scatter',
            data: [],
            symbolSize: 2,
            itemStyle: {
              color: '#1890ff'
            }
          },
          {
            name: '温度趋势',
            type: 'line',
            data: [],
            lineStyle: {
              width: 1,
              color: 'rgba(24, 144, 255, 0.3)'
            },
            symbol: 'none',
            smooth: true
          }
        ],
        grid: {
          left: '3%',
          right: '3%',
          bottom: '35px',
          top: '12%',
          containLabel: true
        }
      };

      this.realtimeChart.setOption(option);

      this.realtimeChart.on('datazoom', (params) => {
        const startValue = params.start !== undefined ? params.start :
          (params.batch && params.batch[0] ? params.batch[0].start : 0);
        const endValue = params.end !== undefined ? params.end :
          (params.batch && params.batch[0] ? params.batch[0].end : 100);

        this.currentZoomRange = {start: startValue, end: endValue};
        this.updateSelectedRangeFromZoom();
      });
    },

    // 更新实时图表
    updateRealtimeChart(meterPoints, temperaturePoints, colors) {
      if (!this.realtimeChart) return;

      const option = {
        xAxis: {
          data: meterPoints
        },
        series: [
          {
            data: temperaturePoints.map((temp, index) => ({
              value: temp,
              itemStyle: {
                color: colors[index]
              }
            }))
          },
          {
            data: temperaturePoints
          }
        ]
      };

      this.realtimeChart.setOption(option);
    },

    // 初始化趋势图表
    initTrendChart() {
      const chartDom = document.getElementById('trendChart');
      if (!chartDom) return;

      this.trendChart = echarts.init(chartDom);
      this.displayEmptyTrendChart();
    },

    // 显示空趋势图表
    displayEmptyTrendChart() {
      const option = {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: {
            color: '#999',
            fontSize: 14,
            fontWeight: 'normal'
          }
        },
        xAxis: {
          type: 'category',
          data: [],
          show: false
        },
        yAxis: {
          type: 'value',
          show: false
        },
        series: []
      };

      if (this.trendChart) {
        this.trendChart.setOption(option, true);
      }

      this.displayedCurves = [];
      this.displayedCurvesCount = 0;
    },

    // 计算时间范围
    calculateTimeRange() {
      const baseTime = this.currentMonitorTime ? new Date(this.currentMonitorTime) : new Date();
      let startTime = new Date(baseTime);
      let endTime = new Date(baseTime);

      switch (this.timeQuery.activeTab) {
        case 'hour':
          startTime.setHours(baseTime.getHours() - this.timeQuery.hour.hours);
          break;
        case 'day':
          if (this.timeQuery.day.dateRange && this.timeQuery.day.dateRange.length === 2) {
            // 开始时间设置为当天的 00:00:00
            startTime = new Date(this.timeQuery.day.dateRange[0]);
            startTime.setHours(0, 0, 0, 0);
            // 结束时间设置为当天的 23:59:59
            endTime = new Date(this.timeQuery.day.dateRange[1]);
            endTime.setHours(23, 59, 59, 999);
          } else {
            // 默认最近7天
            startTime.setDate(baseTime.getDate() - 7);
            startTime.setHours(0, 0, 0, 0);
            endTime.setHours(23, 59, 59, 999);
          }
          break;
        case 'month':
          if (this.timeQuery.month.monthRange && this.timeQuery.month.monthRange.length === 2) {
            startTime = new Date(this.timeQuery.month.monthRange[0] + '-01');
            startTime.setHours(0, 0, 0, 0);
            const endMonth = new Date(this.timeQuery.month.monthRange[1] + '-01');
            endTime = new Date(endMonth.getFullYear(), endMonth.getMonth() + 1, 0);
            endTime.setHours(23, 59, 59, 999);
          } else {
            startTime.setMonth(baseTime.getMonth() - 1);
            startTime.setDate(1);
            startTime.setHours(0, 0, 0, 0);
            endTime.setHours(23, 59, 59, 999);
          }
          break;
        default:
          startTime.setHours(baseTime.getHours() - 1);
      }

      this.trendStartTime = this.formatDateTime(startTime);
      this.trendEndTime = this.formatDateTime(endTime);
    },

    // 格式化日期时间
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 格式化显示时间
    formatDisplayTime(timeString) {
      if (!timeString) return '';
      const date = new Date(timeString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-');
    },

    // 初始化默认时间范围
    initDefaultTimeRange() {
      const now = new Date();
      const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);

      this.timeQuery.hour.hours = 1;
      this.timeQuery.day.dateRange = [
        this.formatDate(oneHourAgo),
        this.formatDate(now)
      ];
      this.timeQuery.month.monthRange = [
        this.formatMonth(oneHourAgo),
        this.formatMonth(now)
      ];

      this.calculateTimeRange();
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 格式化月份
    formatMonth(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      return `${year}-${month}`;
    },

    // 时间标签变更
    handleTimeTabChange() {
      this.calculateTimeRange();
      this.updateTimeRangeText();
    },

    // 时间范围变更
    onTimeRangeChange() {
      this.calculateTimeRange();
    },

    // 时间查询
    async handleTimeQuery() {
      this.calculateTimeRange();
      this.updateTimeRangeText();
      await this.applyZoomToTrend();
    },

    // 更新时间范围文本
    updateTimeRangeText() {
      switch (this.timeQuery.activeTab) {
        case 'hour':
          this.timeRangeText = `最近${this.timeQuery.hour.hours}小时数据`;
          break;
        case 'day':
          if (this.timeQuery.day.dateRange && this.timeQuery.day.dateRange.length === 2) {
            this.timeRangeText = `${this.timeQuery.day.dateRange[0]} 至 ${this.timeQuery.day.dateRange[1]}`;
          } else {
            this.timeRangeText = '最近7天数据';
          }
          break;
        case 'month':
          if (this.timeQuery.month.monthRange && this.timeQuery.month.monthRange.length === 2) {
            this.timeRangeText = `${this.timeQuery.month.monthRange[0]} 至 ${this.timeQuery.month.monthRange[1]}`;
          } else {
            this.timeRangeText = '最近1个月数据';
          }
          break;
        default:
          this.timeRangeText = '最近1小时数据';
      }
    },

    // 应用缩放到趋势图
    async applyZoomToTrend() {
      try {
        if (!this.trendStartTime || !this.trendEndTime) {
          this.calculateTimeRange();
        }

        this.updateSelectedRangeFromZoom();

        let response;

        if (this.timeQuery.activeTab === 'hour') {
          response = await getMeterRangeTemperatureData(
            this.filterForm.deviceNo,
            this.filterForm.channelNo,
            this.selectedRange[0],
            this.selectedRange[1],
            this.trendStartTime,
            this.trendEndTime,
            'hour'
          );
        } else if (this.timeQuery.activeTab === 'day') {
          response = await getMeterRangeTemperatureData(
            this.filterForm.deviceNo,
            this.filterForm.channelNo,
            this.selectedRange[0],
            this.selectedRange[1],
            this.trendStartTime,
            this.trendEndTime,
            'day'
          );
        } else if (this.timeQuery.activeTab === 'month') {
          response = await getMeterRangeTemperatureData(
            this.filterForm.deviceNo,
            this.filterForm.channelNo,
            this.selectedRange[0],
            this.selectedRange[1],
            this.trendStartTime,
            this.trendEndTime,
            'month'
          );
        }

        if (response.code === 200) {
          this.filterHighTemperatureCurves(response.data);
          this.$message.success('趋势图已更新');
        } else {
          this.$message.error('获取温度趋势数据失败');
        }
      } catch (error) {
        console.error('加载趋势数据失败:', error);
        this.$message.error('加载趋势数据失败');
      }
    },

    // 过滤高温曲线
    filterHighTemperatureCurves(trendData) {
      if (!trendData || !trendData.meterData || trendData.meterData.length === 0) {
        this.$message.warning('没有趋势数据可显示');
        this.displayEmptyTrendChart();
        return;
      }

      this.trendDataCache = trendData;

      const highTempMeters = [];
      trendData.meterData.forEach(meter => {
        const hasHighTemp = meter.temperatureValues.some(temp => temp > this.temperatureThreshold);
        if (hasHighTemp) {
          highTempMeters.push(meter.meterMark);
        }
      });

      if (highTempMeters.length === 0) {
        this.$message.info(`当前时间段内没有温度超过${this.temperatureThreshold}°C的曲线`);
        this.displayEmptyTrendChart();
        this.updateCurveSelectionFromTrendData(trendData, []);
        return;
      }

      this.updateCurveSelectionFromTrendData(trendData, highTempMeters);
      this.drawFilteredTemperatureTrend(trendData, highTempMeters);
    },

    // 从趋势数据更新曲线选择
    updateCurveSelectionFromTrendData(trendData, selectedMeters) {
      if (!trendData.meterData) return;

      this.availableCurves = trendData.meterData.map(meter => {
        const maxTemp = Math.max(...meter.temperatureValues);
        return {
          meter: meter.meterMark,
          temperature: maxTemp,
          selected: selectedMeters.includes(meter.meterMark)
        };
      });

      this.displayedCurvesCount = selectedMeters.length;
    },

    // 绘制过滤后的温度趋势
    drawFilteredTemperatureTrend(trendData, selectedMeters) {
      if (!trendData || !trendData.meterData) {
        this.$message.warning('没有趋势数据可显示');
        return;
      }

      if (!selectedMeters || selectedMeters.length === 0) {
        this.displayEmptyTrendChart();
        return;
      }

      const filteredMeterData = trendData.meterData.filter(meter =>
        selectedMeters.includes(meter.meterMark)
      );

      if (filteredMeterData.length === 0) {
        this.displayEmptyTrendChart();
        return;
      }

      const timeLabels = trendData.timeLabels || [];
      const meterData = filteredMeterData;

      const series = [];
      const colors = this.generateColors(meterData.length);

      this.displayedCurves = meterData.map((meter, index) => {
        const maxTemp = Math.max(...meter.temperatureValues);
        const color = colors[index];

        return {
          meter: meter.meterMark,
          maxTemp: maxTemp,
          color: color
        };
      }).sort((a, b) => a.meter - b.meter);

      meterData.forEach((meter, index) => {
        const isHighlighted = this.highlightedCurves.includes(meter.meterMark);
        let color, lineWidth, opacity;

        if (isHighlighted) {
          color = colors[index];
          lineWidth = 3;
          opacity = 1;
        } else {
          color = colors[index];
          lineWidth = 1;
          opacity = 0.3;
        }

        series.push({
          name: `米标${meter.meterMark}`,
          type: 'line',
          data: meter.temperatureValues,
          symbol: 'none',
          lineStyle: {
            width: lineWidth,
            color: color,
            opacity: opacity
          },
          smooth: true,
          showSymbol: false
        });
      });

      this.displayedCurvesCount = meterData.length;

      const option = {
        title: {
          show: false
        },
        tooltip: {
          trigger: 'axis',
          confine: true,
          textStyle: {
            fontSize: 10,
            color: '#333'
          },
          formatter: (params) => {
            const sortedParams = params.slice().sort((a, b) => b.value - a.value);

            // 获取当前时间点（第一个参数的时间）
            const currentTime = params[0].axisValue;
            const formattedTime = this.formatTimeLabel(currentTime, this.timeQuery.activeTab);

            let result = `
      <div style="font-size: 11px; font-weight: bold; color: #333; margin-bottom: 8px; border-bottom: 1px solid #eee; padding-bottom: 4px;">
        时间: ${formattedTime}
      </div>
      <div style="display: flex; flex-wrap: wrap; gap: 8px 16px; max-width: none;">
    `;

            sortedParams.forEach(param => {
              if (param.seriesName && !param.seriesName.startsWith('标签-')) {
                const isHighTemp = param.value > this.temperatureThreshold;
                const textStyle = isHighTemp ?
                  'color: #ff4d4f; font-weight: bold;' :
                  'color: #666;';

                result += `
          <div style="display: flex; align-items: center; margin-bottom: 4px;">
            <span style="display: inline-block; width: 8px; height: 8px; background-color: ${param.color}; margin-right: 4px; border-radius: 50%;"></span>
            <span style="${textStyle}">${param.seriesName}: ${param.value}°C</span>
          </div>
        `;
              }
            });
            result += `</div>`;
            return result;
          }
        },
        legend: {
          show: false
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '3%',
          top: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: timeLabels,
          axisLabel: {
            fontSize: 9,
            rotate: 45,
            formatter: (value) => {
              return this.formatTimeLabel(value, this.timeQuery.activeTab);
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '温度 (°C)',
          min: 20,
          max: 100,
          axisLabel: {
            fontSize: 9
          }
        },
        series: series
      };

      if (this.trendChart) {
        this.trendChart.setOption(option, true);
      }
    },

    // 格式化时间标签
    formatTimeLabel(timeString, queryType) {
      if (!timeString) return '';

      try {
        const date = new Date(timeString);
        if (isNaN(date.getTime())) {
          return timeString; // 如果解析失败，返回原字符串
        }

        switch (queryType) {
          case 'hour':
            // 按小时：显示 HH:mm
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            return `${hours}:${minutes}`;

          case 'day':
            // 按天：显示 日-HH
            const day = String(date.getDate()).padStart(2, '0');
            const hour = String(date.getHours()).padStart(2, '0');
            return `${day}-${hour}`;

          case 'month':
            // 按月：显示 月-日
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const monthDay = String(date.getDate()).padStart(2, '0');
            return `${month}-${monthDay}`;

          default:
            // 默认显示 HH:mm
            const defaultHours = String(date.getHours()).padStart(2, '0');
            const defaultMinutes = String(date.getMinutes()).padStart(2, '0');
            return `${defaultHours}:${defaultMinutes}`;
        }
      } catch (error) {
        console.error('格式化时间标签失败:', error);
        return timeString;
      }
    },

    // 生成颜色
    generateColors(count) {
      const baseColors = [
        '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
        '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9',
        '#F8C471', '#82E0AA', '#F1948A', '#85C1E9', '#D7BDE2',
        '#F9E79F', '#A9DFBF', '#F5B7B1', '#AED6F1', '#E8DAEF'
      ];

      const colors = [];
      for (let i = 0; i < count; i++) {
        colors.push(baseColors[i % baseColors.length]);
      }
      return colors;
    },

    // 切换曲线高亮
    toggleCurveHighlight(meter) {
      const index = this.highlightedCurves.indexOf(meter);
      if (index > -1) {
        this.highlightedCurves.splice(index, 1);
      } else {
        this.highlightedCurves.push(meter);
      }

      if (this.trendDataCache) {
        const selectedMeters = this.selectedCurvesList.map(curve => curve.meter);
        this.drawFilteredTemperatureTrend(this.trendDataCache, selectedMeters);
      }
    },

    // 清除所有高亮
    clearAllHighlights() {
      this.highlightedCurves = [];
      if (this.trendDataCache) {
        const selectedMeters = this.selectedCurvesList.map(curve => curve.meter);
        this.drawFilteredTemperatureTrend(this.trendDataCache, selectedMeters);
      }
    },

    // 显示曲线选择器
    showCurveSelector() {
      this.curveSelectorVisible = true;
    },

    // 处理曲线选择器关闭
    handleCurveSelectorClose(done) {
      this.curveSelectorVisible = false;
      if (done) done();
    },

    // 选择温度曲线
    selectTempCurves() {
      this.availableCurves.forEach(curve => {
        curve.selected = curve.temperature >= this.temperatureThreshold;
      });
    },

    // 选择所有曲线
    selectAllCurves() {
      this.availableCurves.forEach(curve => {
        curve.selected = true;
      });
    },

    // 移动到已选择
    moveAllToSelected() {
      this.availableCurves.forEach(curve => {
        curve.selected = true;
      });
    },

    // 移动到可用
    moveAllToAvailable() {
      this.availableCurves.forEach(curve => {
        curve.selected = false;
      });
    },

    // 清除所有曲线
    clearAllCurves() {
      this.availableCurves.forEach(curve => {
        curve.selected = false;
      });
    },

    // 切换曲线选择
    toggleCurveSelection(curve) {
      curve.selected = !curve.selected;
    },

    // 确认曲线选择
    confirmCurveSelection() {
      this.selectedCurves = this.selectedCurvesList.map(curve => curve.meter);
      this.displayedCurvesCount = this.selectedCurves.length;

      if (this.trendDataCache) {
        this.drawFilteredTemperatureTrend(this.trendDataCache, this.selectedCurves);
      }

      this.curveSelectorVisible = false;
      this.$message.success(`已选择${this.selectedCurves.length}条曲线`);
    }
  }
};
</script>

<style scoped>
.temperature-monitor-compact {
  display: flex;
  gap: 12px;
  padding: 8px;
  background: #f5f7fa;
}

.temperature-monitor-compact.layout-row {
  flex-direction: row;
  height: 100%;
}

.temperature-monitor-compact.layout-row .chart-card {
  flex: 1;
  min-width: 0;
  width: 50%; /* 各占50% */
}

.temperature-monitor-compact.layout-column {
  flex-direction: column;
}

.temperature-monitor-compact.layout-column .chart-card {
  width: 100%;
}

.layout-column {
  flex-direction: column;
}

.layout-row {
  flex-direction: row;
}

.chart-card.compact {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 350px; /* 添加最小高度 */
}

.chart-card.compact ::v-deep .el-card__body {
  flex: 1;
  display: flex;
  flex-direction: column;
}

#realtimeChart, #trendChart {
  flex: 1;
  min-height: 0; /* 重要：允许收缩 */
}

.card-header.compact {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0 !important;
  min-height: auto;
}

.chart-title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chart-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.monitor-time {
  font-size: 12px;
  color: #606266;
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 3px;
}

.filter-controls {
  display: flex;
  align-items: center;
}

.compact-form {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 0 !important;
}

.compact-form ::v-deep .el-form-item {
  margin-bottom: 0 !important;
}

.chart-legend {
  display: flex;
  gap: 12px;
  align-items: center;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #606266;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-color.normal {
  background-color: #1890ff;
}

.legend-color.warning {
  background-color: #faad14;
}

.legend-color.danger {
  background-color: #ff4d4f;
}

.trend-header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.meter-range {
  font-size: 12px;
  color: #909399;
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 3px;
}

.trend-header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.time-range {
  font-size: 12px;
  color: #606266;
}

.time-query-section.single-line {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
  padding: 6px 0;
  border-bottom: 1px solid #ebeef5;
}

.query-type-buttons {
  display: flex;
}

.query-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.query-control-group {
  display: flex;
  align-items: center;
  gap: 4px;
}

.query-label {
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
}

.query-unit {
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
}

.query-button {
  margin-left: auto;
}

.trend-chart-container {
  display: flex;
  gap: 12px;
  height: 220px;
}

.curve-list-panel {
  width: 180px;
  background: #fafafa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.curve-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 8px;
  background: #f0f2f5;
  border-bottom: 1px solid #ebeef5;
  font-size: 12px;
  font-weight: 500;
}

.curve-list-content {
  flex: 1;
  overflow-y: auto;
  padding: 4px;
}

.curve-list-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 6px;
  margin-bottom: 2px;
  border-radius: 3px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 11px;
}

.curve-list-item:hover {
  background: #e6f7ff;
}

.curve-list-item.highlighted {
  background: #1890ff;
  color: white;
}

.curve-color-indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  flex-shrink: 0;
}

.curve-info {
  flex: 1;
  display: flex;
  flex-direction: row;
  align-items: center; /* 垂直居中 */
  gap: 8px; /* 元素间距 */
}

.meter-number {
  font-weight: 500;
  white-space: nowrap; /* 防止换行 */
}

.max-temperature {
  color: #909399;
  font-size: 10px;
  white-space: nowrap; /* 防止换行 */
}

.curve-list-item.highlighted .max-temperature {
  color: rgba(255, 255, 255, 0.8);
}

.empty-list {
  text-align: center;
  color: #909399;
  font-size: 12px;
  padding: 20px 0;
}

.curve-selector-content {
  padding: 0;
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.selector-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.curve-selector-layout {
  display: flex;
  gap: 16px;
  height: 400px;
}

.curve-panel {
  flex: 1;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
  font-size: 13px;
  font-weight: 500;
}

.curve-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.curve-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 8px;
  margin-bottom: 4px;
  border: 1px solid #e4e7ed;
  border-radius: 3px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 12px;
}

.curve-item:hover {
  border-color: #1890ff;
  background: #f0f7ff;
}

.curve-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.meter-number {
  font-weight: 500;
}

.temperature {
  color: #606266;
}

.temperature.high-temp {
  color: #ff4d4f;
  font-weight: 500;
}

.select-icon, .remove-icon {
  color: #c0c4cc;
  font-size: 12px;
}

.transfer-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 8px;
  padding: 0 8px;
}

/* 确保圆形按钮保持圆形 */
.transfer-actions .el-button--mini.is-circle {
  width: 28px !important;  /* 固定宽度 */
  height: 28px !important; /* 固定高度 */
  min-width: 28px !important; /* 最小宽度 */
  padding: 0 !important; /* 移除内边距 */
  flex-shrink: 0; /* 防止flex收缩 */
}

.compact-dialog ::v-deep .el-dialog__body {
  padding: 15px 20px;
}

.compact-dialog ::v-deep .el-dialog__footer {
  padding: 10px 20px 15px;
}
</style>
